/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData, pickedVertexData } from '@amcax/base';
import { previewer } from '@app-cad/module';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import {
  MULTI_SOLUTION_SCHEMA,
  MultiSolutionWidget,
} from '@app-cad/common/components/command-form/widgets/multi-solution';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useMemo, useState } from 'react';

type FormData = {
  profile: pickedLineData[];
  spline1?: pickedLineData;
  point?: pickedVertexData;
  spline2?: pickedLineData;
  closed: boolean;
};

type Params = {
  profile: string[];
  spline: {
    id1: string;
    point: string;
    id2: string;
    closed: boolean;
  };
  solution: number;
};

function CommandDoubleTrackSweep({
  title,
  onClose,
  props,
}: CurvedCmdDialogParams) {
  const initData: FormData = {
    profile: [],
    closed: false,
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const [solutionNum, setSolutionNum] = useState(0);
  const [solution, setSolution] = useState(0);

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { profile, spline, solution } = params;

    await initEditDependency([
      ...profile,
      spline.id1,
      spline.id2,
      spline.point,
    ]);

    setFormData({
      profile: profile.map(
        (p) => picker.generatePickObjByPickID(p) as pickedLineData,
      ),
      spline1: picker.generatePickObjByPickID(spline.id1, {
        showArrow: true,
      }) as pickedLineData,
      spline2: picker.generatePickObjByPickID(spline.id2, {
        showArrow: true,
      }) as pickedLineData,
      point: picker.generatePickObjByPickID(spline.point) as pickedVertexData,
      closed: spline.closed,
    });

    setSolution(solution);
  }, [props?.shape]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, isLoading } =
    useCommand('cmd-monorail-sweep', {
      onClose,
      finishDraw: checkAndFinishDraw,
      commandName: 'CreateSurface',
      editDxid: props?.shape,
    });

  const execute = (preview: boolean) => {
    const { profile, spline1, spline2, closed, point } = formData;
    const params = {
      type: 'DoubleTrackSweep',
      a: {
        profile: profile.map((v) => v.edgeId),
        spline: {
          id1: spline1.edgeId,
          id2: spline2.edgeId,
          point: point.vertexId,
          closed,
        },
        solution,
      } as Params,
    };

    return confirmCommand(params, preview);
  };

  const isFormDataValid = () => {
    const { profile, spline1, spline2 } = formData;

    return profile?.length > 0 && spline1 != null && spline2 != null;
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      previewer.clear();
      return;
    }

    const { nsolution } = await execute(true);

    setSolutionNum(nsolution);
  };

  useAsyncEffect(preview, [solution]);

  const finalFormData = useMemo(
    () => ({
      ...formData,
      solution: [solution, solutionNum],
    }),
    [formData, solution, solutionNum],
  );

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      profile: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        format: PickInputRJSFFormat.MultiPickCurve,
        uniqueItems: true,
      },
      spline1: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      point: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      spline2: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      closed: {
        title: '闭合曲线扫掠',
        type: 'boolean',
        default: false,
      },
      solution: MULTI_SOLUTION_SCHEMA,
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={finalFormData}
      submitLoading={isLoading}
      onChange={(v) => {
        setFormData(v);
        setSolution(v.solution[0]);
      }}
      extraUiSchema={{
        profile: {
          'ui:placeholder': '扫掠形状',
          'ui:autofocus': true,
        },
        spline1: {
          'ui:placeholder': '路径1',
          'ui:options': {
            showArrow: true,
          },
        },
        point: {
          'ui:placeholder': '路径1上的点',
        },
        spline2: {
          'ui:placeholder': '路径2',
          'ui:options': {
            showArrow: true,
          },
        },
        solution: {
          'ui:widget': MultiSolutionWidget,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdDoubleTrackSweep: CurvedBaseCommand = {
  id: 'cmdDoubleTrackSweep',
  label: 'command.double-track-sweep',
  icon: 'commands/curved/double-track-sweep',
  create: (label, onClose, props) => (
    <CommandDoubleTrackSweep
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
